package org.sensornet2010.co2sh.core;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class SensornetUtil {

	public static String LOG_FILE = SoundRecorder.DIRECTORY + "ASensornet.log"; 
	
	public static void debug(String message){
		//Log.v("sensornet", message);
		System.err.println("sensornet:" + message);
		Date date = new Date();
		try {
			writeToFile(LOG_FILE, date.toGMTString() + ":" + message + "\n", true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void debugException(Exception exception){
		exception.printStackTrace();
		debug("error:" + exception.getMessage());
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			PrintWriter pw = new PrintWriter(out);
			exception.printStackTrace(pw);
			pw.close();
			String trace = new String(out.toByteArray());
			debug(trace);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void writeToFile(String fileFullPath, String content, boolean append) throws IOException {
		FileWriter fw = new FileWriter(fileFullPath, append);
		fw.append(content);
		fw.close();
	}
	
	
	private static class DummyListener implements iSensornetAppListener{
		public void sensorAction(int type, String info) {
			SensornetUtil.debug("DummyListener: sensorAction:" + type + ":" + info);
		}
	}
	
	private static class DummyFileSoundRecorder extends SoundRecorder{
		private String testAmrFile = null;
		private DummyFileSoundRecorder (long duration) {
			super(duration);
		}
		public byte[] record() throws Exception {
			SensornetUtil.debug("DummyFileSoundRecorder:file=" + testAmrFile);
			File file = new File(testAmrFile);
			return SensornetUtil.getBytesFromFile(file);
		}
	}
	private static class DummySoundDecoder extends SoundDecoder{
		private String testWavFile = null;
		public DummySoundDecoder() {
			super(null);
		}

		protected byte[] convertAmr2Wav(byte[] amrSound) {
			File file = new File(testWavFile);
			try {
				SensornetUtil.debug("DummySoundDecoder:file=" + testWavFile);
				return SensornetUtil.getBytesFromFile(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	/**
	 * Gets bytes from a file.
	 * @param file				File
	 * @return bytes			byte[]
	 * @throws IOException
	 */
	public static byte[] getBytesFromFile(File file) throws IOException {
		// Code snippet from
		// http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html 
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }	
	
	private static void testPachube() throws Exception{
		// http://community.pachube.com/quickstart
		String server = "http://localhost";
		String feed = "/v2/feeds/12698.csv";
		String API_KEY ="";
		
		String url = server + feed + "?key=" + API_KEY;
		URL u = new URL(url);
		HttpURLConnection hc = (HttpURLConnection)u.openConnection(); 
		hc.setRequestMethod("PUT");
		hc.setDoOutput(true);
	    hc.setDoInput(true);
	    //hc.setAllowUserInteraction(false);
	    Date date = new Date();
	    String content = "0," + date.getTime();
	    byte[] postBytes = content.getBytes();
		OutputStream dout = hc.getOutputStream();
		dout.write(postBytes);
		dout.close();
		debug("closed");
		int ch;
		InputStream is = hc.getInputStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((ch = is.read()) != -1) {
			bos.write(ch);
		}
		String response = new String(bos.toByteArray());
		debug(response);
	}
	
	
	public static void main(String[] args) {
		System.err.println("SensornetUtil main()");
		// load configuration
		SensornetConfiguration.RECORDING_INTERVAL = 10;
		//RemoteServer.CGI_AMR2WAV = "uploaded.php";
		// Creating dummies
		iSensornetAppListener listener = new DummyListener();
		String amrFile = "../677Hz.3gpp";
		DummyFileSoundRecorder recorder = new DummyFileSoundRecorder(SensornetConfiguration.RECORDING_DURATION);
		recorder.testAmrFile = amrFile;
		DummySoundDecoder decoder = new DummySoundDecoder();
		String wavFile = "../1460.wav";
		decoder.testWavFile = wavFile;
		
		// create app object
		SensornetApp app = new SensornetApp();
		app.setListener(listener);
		app.recorder = recorder;
		//app.server.decoder = decoder;
		app.start();
		// wait doing nothing
		try {
			Thread.sleep(25 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
